﻿using D.B.Data.API.Applications.Command.RoleMenusCommand;
using D.B.Data.Domain;
using D.B.Data.Domain.DTO.Output;
using D.B.Data.ErrorCode;
using D.B.Data.Infrastructuse;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;

namespace D.B.Data.API.Applications.CommandHandler.RoleMenusCommandHandler
{
    public class UserRoleMenusCommandHandler : IRequestHandler<UserRoleMenusCommand, APIResult<List<RoleIdMenusDTO>>>
    {

        private readonly IBaseRepository<MenusModel> baseRepository;
        private readonly IBaseRepository<RoleMenusModel> rolemenusRepository;

        public UserRoleMenusCommandHandler(IBaseRepository<MenusModel> baseRepository, IBaseRepository<RoleMenusModel> rolemenusRepository)
        {
            this.baseRepository = baseRepository;
            this.rolemenusRepository = rolemenusRepository;
        }

        public Task<APIResult<List<RoleIdMenusDTO>>> Handle(UserRoleMenusCommand request, CancellationToken cancellationToken)
        {
            var list=request.RIe.Split(',').ToList();
            var rolemenusQuery = rolemenusRepository.GetAll();
            List<long> model = new List<long>();
            //获取菜单Id
            foreach (var item in list)
            {
                var mIds = rolemenusQuery.Where(s => s.RID ==Convert.ToInt64(item)).Select(s => s.MID).ToList();
                model.AddRange(mIds);
            }

            long aa =0;
            List<long> model2 = new List<long>();
            foreach (var item in model)
            {
                 aa = baseRepository.GetAll().FirstOrDefault(s => s.Id == item).Pid;
                model2.Add(aa);
            }

            model.AddRange(model2);


            var menusQuery = baseRepository.GetAll().Where(s=>!s.IsDel);
            var data = Find(0, menusQuery.ToList(), model);

            APIResult<List<RoleIdMenusDTO>> result = new APIResult<List<RoleIdMenusDTO>>()
            {
                Code=EnumCode.Ok,
                Msg="成功",
                Data=data   
            };

            return Task.FromResult(result);
        }

        public List<RoleIdMenusDTO> Find(long id, List<MenusModel> ids,List<long> mId)
        {
            var res = ids.Where(s => s.Pid == id&& mId.Contains(s.Id)).ToList();

            List<RoleIdMenusDTO> menus = new List<RoleIdMenusDTO>();

            foreach (var item in res)
            {
                menus.Add(new RoleIdMenusDTO
                {
                   Index=item.Url,
                   Name=item.MenuName,
                   Children= Find(item.Id,ids, mId)
                });
            }

            return menus;
        }
    }
}
